package com.leTest.eduService.controller;

import com.leTest.R;
import com.leTest.client.VodClient;
import com.leTest.eduService.entity.VideoEntity;
import com.leTest.eduService.service.VideoService;
import com.leTest.exceptionhandler.CustomExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author le
 * @since 2025-02-16
 */
@RestController
@RequestMapping("/eduService/video")
@CrossOrigin
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private VodClient vodClient;

    @PostMapping("addVideo")
    public R addVideo(@RequestBody VideoEntity videoEntity) {
        videoService.save(videoEntity);
        return R.ok();
    }

    //删除小节
    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable String id) {
        //1.1根据小节id得到视频id
        VideoEntity eduVideo = videoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        //1.2根据视频id,远程调用实现视频删除(线判断id不为空才调用方法删除)
        if (!StringUtils.isEmpty(videoSourceId)) {
            R result = vodClient.removeAlyVideo(videoSourceId);
            if (result.getCode() == 100) {
                throw new CustomExceptionHandler(100, "根据单个视频id删除视频失败,熔断器...");
            }

        }

        videoService.removeById(id);
        return R.ok();
    }

    //根据小节id查询
    @GetMapping("getVideoInfo/{videoId}")
    public R getVideoInfo(@PathVariable String videoId) {
        VideoEntity eduVideo = videoService.getById(videoId);
        return R.ok().data("video", eduVideo);
    }

    //修改小节
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody VideoEntity eduVideo) {
        videoService.updateById(eduVideo);
        return R.ok();
    }

}
